package com.infrastructure.net;

import android.app.Activity;
import android.content.res.XmlResourceParser;

import com.infrastructure.R;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by zyt on 16/6/14 11:37 .
 * Email : syy19930112@aliyun.com
 * Description:
 * <p/>
 * 管理url的配置
 */
public final class UrlConfigManager {

    private static ArrayList<URLData> urlList;

    private UrlConfigManager() {

    }

    /**
     * 根据findKey,获取对应的{@link URLData}对象
     *
     * @param activity
     * @param findKey
     * @return
     */
    public static final URLData findURL(final Activity activity, final String findKey) {
        // 如果urlList还没有数据（第一次)
        // 或者被回收了，那么（重新）加载xml
        if (urlList == null || urlList.isEmpty())
            fetchUrlDataFromXml(activity);
        for (URLData data : urlList) {
            if (findKey.equals(data.getKey())) {
                return data;
            }
        }
        return null;
    }

    /**
     * 一次性从配置文件中取出url数据
     *
     * @param activity
     */
    public static void fetchUrlDataFromXml(Activity activity) {
        final XmlResourceParser xmlParser = activity.getApplication()
                .getResources().getXml(R.xml.url);
        int eventCode;
        try {
            eventCode = xmlParser.getEventType();
            while (eventCode != XmlPullParser.END_DOCUMENT) {
                switch (eventCode) {
                    case XmlPullParser.START_DOCUMENT:
                        urlList = new ArrayList<>();
                        break;
                    case XmlPullParser.START_TAG:
                        if ("Node".equals(xmlParser.getName())) {
                            final URLData urlData = new URLData();
                            urlData.setKey(xmlParser.getAttributeValue(null, "Key"));
                            urlData.setExpires(Long.parseLong(xmlParser
                                    .getAttributeValue(null, "Expires")));
                            urlData.setNetType(xmlParser.getAttributeValue(
                                    null, "NetType"));
                            urlData.setUrl(xmlParser.getAttributeValue(null,
                                    "Url"));
                            urlList.add(urlData);
                        }
                }
                eventCode = xmlParser.next();
            }
        } catch (final XmlPullParserException e) {
            e.printStackTrace();
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            xmlParser.close();
        }
    }
}
